﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Casamiel.API.Application.Models.V2;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MediatR;
using Casamiel.Application.Commands;
using Casamiel.API.Application.Commands;
using Casamiel.Common;
using Casamiel.API.Infrastructure.Middlewares;
using Casamiel.API.Application.Models;
using Casamiel.Domain.Response;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Casamiel.API.Controllers.V2
{
    /// <summary>
    /// App wechat login controller.
    /// </summary>
    [Produces("application/json")]
    [ApiVersion("2.0")]
    [Route("api/v{api-version:apiVersion}/[controller]")]
    [Authorize]
    [ApiController]

    public class AppWechatLoginController : BaseController
    {
        private readonly IMediator _mediator;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="mediator">Mediator.</param>
        public AppWechatLoginController(IMediator mediator)
        {
            _mediator = mediator;
        }

        /// <summary>
        /// Login this instance.
        /// </summary>
        /// <returns>The login.</returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<ActionResult<BaseResult<AppWechatLoingRsp>>>Login([FromBody] AppWechatLoginReq req)
        {
            if (req == null)
            {
                throw new ArgumentNullException(nameof(req));
            }

            var source = 1;
            var loginifo =this.LoginInfo;
            //var userAgent = Request.Headers["User-Agent"].ToString() == "" ? Request.Headers["UserAgent"].ToString() : Request.Headers["User-Agent"].ToString();
            //int loginType = userAgent.Contains("CASAMIEL") ? 1 : 2;
            int loginType = loginifo.Item1;
            source = loginifo.Item2;
            var command = new AppWecahtLoginCommand(req.AppId, req.Code,LoginInfo.Item3) {RequestUrl=Request.GetShortUri(), Source = source };
            var result = await _mediator.Send(command).ConfigureAwait(false);
            AppWechatLoingRsp rsp;
            if (!result.Item2)
            {
                rsp = new AppWechatLoingRsp { Id = result.Item1, IsReg = result.Item2 };
            }
            else
            {
                var commandlogin = new LoginCommand { Mobile = result.Item3, LoginType = loginType, Registration_Id = req.Registration_Id, RequestUrl = Request.GetShortUri(), UserIP = Request.GetUserIp(), Source = source };
                var resultlogin = await _mediator.Send(commandlogin).ConfigureAwait(false);
                var member = resultlogin.Item1;
                //var memberdata = new { Mobile = member.Mobile, Nick = member.Nick, Birthday = member.Birthday, Sex = member.Sex, TrueName = member.TrueName, Email = member.Email, cardno = result.Item3 };
                rsp = new AppWechatLoingRsp { Id = result.Item1, IsReg = result.Item2,data=resultlogin.Item2, member = member };
            }
            return new BaseResult<AppWechatLoingRsp>(rsp, 0, "");
        }
        /// <summary>
        /// Binds the mobile.
        /// </summary>
        /// <returns>The mobile.</returns>
        /// <param name="req">Req.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> BindMobile([FromBody] BindMobileReq req)
        {
            if (req == null)
            {
                throw new ArgumentNullException(nameof(req));
            }

            var source = 1;
            var userAgent = string.IsNullOrEmpty(Request.Headers["User-Agent"].ToString()) ? Request.Headers["UserAgent"].ToString() : Request.Headers["User-Agent"].ToString();
            int loginType = userAgent.ToUpper().Contains("CASAMIEL",  StringComparison.CurrentCultureIgnoreCase) ? 1 : 2;
            if (loginType == 1)
            {
                source = 1;
            }
            if (userAgent.Contains("MicroMessenger", StringComparison.CurrentCultureIgnoreCase))
            {
                loginType = 3;
                source = 2;
            }
            var command = new AppWechatLoginBindMobileCommand(req.Id, req.Mobile, req.Yzm,LoginInfo.Item3);
            var result = await _mediator.Send(command).ConfigureAwait(false);
            if (result.Item1)
            {
                var commandlogin = new LoginCommand { Mobile = req.Mobile, LoginType = loginType, Registration_Id = req.Registration_Id, RequestUrl = Request.GetShortUri(), UserIP = Request.GetUserIp(), Source = source };
                var resultlogin = await _mediator.Send(commandlogin).ConfigureAwait(false);
                var member = resultlogin.Item1;
                var memberdata = new { Mobile = member.Mobile, Nick = member.Nick, Birthday = member.Birthday, Sex = member.Sex, TrueName = member.TrueName, Email = member.Email, cardno = resultlogin.Item3 };
                return Ok(new { code = 0, data = resultlogin.Item2, member = memberdata });
            }
            else
            {
                return Ok(new BaseResult<string>("", 999,result.Item2 ));
            }
             
        }
    }
     
}
